<template>
  <Loader :loading="loading" text="加载中...">
    <view class="consult-detail-page">
      <!-- 咨询信息 -->
      <view class="consult-info">
        <view class="info-section">
          <!-- 状态与问题类型按信息项展示 -->
          <view class="info-content">
            <view class="info-item">
              <text class="info-label">工单状态：</text>
              <view class="status-type-line">
                <view class="status-tag">
                  <text class="tag-text">{{ getStatusText(consultData.status) }}</text>
                </view>
              </view>
            </view>
            <view class="info-item">
              <text class="info-label">问题类型：</text>
              <view class="question-type-tags">
                <view v-for="type in getQuestionTypeLabels(consultData.question_types)" :key="type"
                  class="question-type-tag">
                  <text class="tag-text">{{ type }}</text>
                </view>
              </view>
            </view>
          </view>

          <view class="info-content">
            <!-- 用户与专家信息展示 -->
            <view v-if="isExpert && consultData.user_info" class="info-item">
              <text class="info-label">用户信息：</text>
              <view class="user-expert-box">
                <image v-if="consultData.user_info.avatar" class="avatar" :src="consultData.user_info.avatar"
                  mode="aspectFill" />
                <text class="info-value">{{ consultData.user_info.nickname }}</text>
              </view>
            </view>
            <view v-if="consultData.expert_info" class="info-item">
              <text class="info-label">负责专家：</text>
              <view class="user-expert-box">
                <image v-if="consultData.expert_info.avatar" class="avatar" :src="consultData.expert_info.avatar"
                  mode="aspectFill" />
                <text class="info-value">{{ consultData.expert_info.nickname }}</text>
              </view>
            </view>

            <view class="info-item">
              <text class="info-label">创建时间：</text>
              <text class="info-value">{{ formatDate(consultData.created_at) }}</text>
            </view>
          </view>

          <view class="description-section">
            <text class="description-label">问题描述</text>
            <text class="description-content">{{ consultData.description }}</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮区域（统一以用户逻辑为准） -->
      <view class="action-section">
        <view class="user-actions">
          <button v-if="consultData.status === 1 && isExpert" class="action-button primary" @click="claimConsult">
            认领咨询
          </button>
          <button v-if="consultData.status === 2" class="action-button primary" @click="enterConsultation">
            进入咨询室
          </button>
          <button v-else-if="consultData.status === 3" class="action-button secondary" @click="viewConsultation">
            查看咨询记录
          </button>
        </view>
      </view>
    </view>
  </Loader>
</template>

<script>
import { identity } from '@/util/identity.js'
import { requests } from '@/util/request.js'
import Loader from '@/components/Loader/Loader.vue'
import consultConfig from '@/static/config/consult_config.json'

export default {
  name: "ConsultDetail",
  components: { Loader },
  data() {
    return {
      consultId: null,
      consultData: {},
      isExpert: false,
      loading: false
    };
  },
  methods: {
    // 获取问题类型标签数组
    getQuestionTypeLabels(questionTypes) {
      if (!questionTypes || !Array.isArray(questionTypes)) {
        return ['未分类'];
      }

      // 根据配置映射中文标签
      const typeLabels = questionTypes.map(type => {
        if (consultConfig && consultConfig.question_types && consultConfig.question_types[type]) {
          return consultConfig.question_types[type].cn;
        }
        return type; // 如果配置中没有找到，返回原值
      }).filter(label => label);

      return typeLabels.length > 0 ? typeLabels : ['未分类'];
    },

    // 获取咨询详情
    async loadConsultDetail() {
      this.loading = true;
      try {
        const res = await requests.request({
          url: `/consultation/ticket/get/?ticket_id=${this.consultId}`,
          method: 'GET'
        });
        const d = res?.data?.ticket || res?.data || {};
        let statusVal = d.status;
        if (typeof statusVal === 'string') {
          const map = { seeking: 1, progress: 2, resolved: 3 };
          statusVal = map[statusVal] ?? 1;
        }
        if (typeof statusVal !== 'number') {
          statusVal = Number(statusVal);
          if (Number.isNaN(statusVal)) statusVal = 1;
        }
        this.consultData = {
          id: d.id ?? this.consultId,
          title: d.title ?? d.subject ?? '',
          question_types: d.question_types ?? [],
          user_info: typeof d.user_info === 'object' ? d.user_info : null,
          description: d.description ?? d.content ?? '',
          status: statusVal,
          created_at: d.created_at ?? d.create_time ?? d.createdAt ?? '',
          updated_at: d.updated_at ?? d.update_time ?? d.updatedAt ?? '',
          user: d.user ?? d.user_id ?? '',
          expert_info: typeof d.expert_info === 'object' ? d.expert_info : null
        };
      } catch (error) {
        console.error('获取咨询详情失败:', error);
        uni.showToast({
          title: '获取咨询详情失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 认领咨询（专家操作）
    async claimConsult() {
      this.loading = true;

      try {
        await requests.request({
          url: '/consultation/ticket/claim/',
          method: 'POST',
          data: { ticket_id: Number(this.consultId) }
        });
        uni.showToast({
          title: '认领成功',
          icon: 'success'
        });

        // 刷新页面数据
        this.loadConsultDetail();

      } catch (error) {
        console.error('认领咨询失败:', error);
        const msg = error?.data?.error || '认领失败，请重试';
        uni.showToast({
          title: msg,
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 进入咨询
    enterConsultation() {
      uni.navigateTo({
        url: `/sub_pages/pages/consultation/consultation?id=${this.consultId}`
      });
    },

    // 查看咨询记录
    viewConsultation() {
      uni.navigateTo({
        url: `/sub_pages/pages/consultation/consultation?id=${this.consultId}&view=true`
      });
    },

    // 获取状态样式类
    getStatusClass(status) {
      const statusMap = {
        1: 'status-seeking',    // 寻找专家
        2: 'status-progress',   // 解决中
        3: 'status-resolved'    // 已解决
      };
      return statusMap[status] || 'status-default';
    },

    // 获取状态文本
    getStatusText(status) {
      if (consultConfig && consultConfig.ticket_status && consultConfig.ticket_status[status]) {
        return consultConfig.ticket_status[status];
      }
      return '未知状态';
    },

    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    }
  },

  onLoad(options) {
    this.consultId = options.ticketId;
    this.isExpert = identity.isHealthTeam();
    this.loadConsultDetail();
  }
};
</script>

<style scoped>
.consult-detail-page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  padding: 20rpx 0;
  text-align: center;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.consult-info {
  margin-top: 20rpx;
}

.info-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30rpx;
}

.consult-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  margin-right: 20rpx;
}

.consult-status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.status-type-line {
  display: flex;
  align-items: center;
}

.status-tag {
  background-color: #ffe8ec;
  /* light pink */
  color: #F26A77;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
}

.status-seeking {
  background-color: #fff3cd;
  color: #856404;
}

.status-progress {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-resolved {
  background-color: #d4edda;
  color: #155724;
}

.status-text {
  font-size: 24rpx;
}

.info-content {
  margin-bottom: 30rpx;
}

.info-item {
  display: flex;
  margin-bottom: 16rpx;
}

.info-label {
  font-size: 28rpx;
  color: #666;
  width: 160rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.status-types-row {
  margin-bottom: 20rpx;
}

.question-type-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
  flex: 1;
}

.question-type-tag {
  background-color: #ffe8ec;
  /* light pink background */
  color: #F26A77;
  /* main pink */
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
}

.tag-text {
  font-size: 24rpx;
  color: #F26A77;
  /* main pink */
}

.user-expert-box {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
}

.description-section {
  border-top: 1rpx solid #f0f0f0;
  padding-top: 30rpx;
}

.description-label {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
  display: block;
}

.description-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.action-section {
  margin-top: 40rpx;
  padding: 0 20rpx;
}

.expert-actions,
.user-actions {
  display: flex;
  gap: 20rpx;
}

.action-button {
  flex: 1;
  height: 88rpx;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.action-button.primary {
  background-color: #F26A77;
  /* main pink */
  color: white;
}

.action-button.primary:active {
  background-color: #d95763;
  /* darker pink */
}

.action-button.secondary {
  background-color: #6c757d;
  color: white;
}

.action-button.secondary:active {
  background-color: #545b62;
}
</style>
